<template>
	<div>
		<h2>采购名称</h2>
		<el-input v-model="PurchaseName" style="margin-bottom: 20px; margin-top: 10px"></el-input>
		<h2 style="margin-bottom: 10px">选择产品</h2>
		<el-table :data="tableData" ref="table" @selection-change="onSelectionChange">
			<el-table-column type="selection" width="55"></el-table-column>
			<el-table-column v-for="(column, index) in columns" :key="index" :prop="column.prop" :label="column.label">
				<template #default="{ row }">
					<template v-if="index !== 5">
						{{ row[column.prop] }}
					</template>
					<template v-else>
						<el-input
							v-model.number="row.NewBuyAmount"
							type="number"
							:min="column.min"
							:max="row.Amount"
							:precision="0"
							@change="updateNumber(row)"
						></el-input>
					</template>
				</template>
			</el-table-column>
			<el-table-column label="总金额">
				<template #default="{ row }">
					{{ calculateTotalAmount(row) }}
				</template>
			</el-table-column>
		</el-table>
		<br />
		<el-button type="primary" @click="submitData">提交</el-button>

		<el-dialog v-model="dialogVisible" title="已选商品" @close="handleClose">
			<el-table :data="selectedRows">
				<el-table-column prop="ProductID" label="商品名"></el-table-column>
				<el-table-column prop="Unit" label="单位"></el-table-column>
				<el-table-column prop="Price" label="单价"></el-table-column>
				<!-- 状态不能是取消的  下达数量 -->
				<el-table-column prop="Amount" label="采购数量"></el-table-column>
				<el-table-column prop="BuyAmount" label="下达数量"></el-table-column>
				<el-table-column prop="UseTime" label="已下达数量"></el-table-column>
				<el-table-column prop="TotalAmount" label="总金额">
					<template #default="{ row }">
						{{ calculateTotalAmount(row) }}
					</template>
				</el-table-column>
			</el-table>
			<template #footer>
				<el-button type="primary" @click="handleClose">完成</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script>
import { ref, nextTick } from 'vue';
import { ElInput, ElTable, ElTableColumn, ElButton, ElDialog, ElMessage } from 'element-plus';
import { httpReqeustApi } from '/@/api/linxyun/base';
import { useRouter } from 'vue-router';
export default {
	components: {
		ElInput,
		ElTable,
		ElTableColumn,
		ElButton,
		ElDialog,
	},
	setup() {
		const httpRequest = httpReqeustApi();
		const supplierName = ref([]);
		const router = useRouter();
		const query = router.currentRoute.value.query;
		// 获取 from 参数值
		const from = query.from;
		if (!from) return ElMessage.error('缺少from参数');
		console.log('from', from, query); // "903_104"
		let SupplierInfo = sessionStorage.getItem(from);
		//转换成数组
		const obj = JSON.parse(SupplierInfo);
		const fullSupplierInfo = ref();

		const state = reactive({
			PurchaseName: '',
		});
		const queryData = () => {
			httpRequest.Get('querySupplier', { SupplierID: obj.select }).then((res) => {
				if (res.success && res.Records?.length) fullSupplierInfo.value = res.Records[0] || {};
			});
			httpRequest.Get('querySupplierName', { SupplierID: obj.select }).then((res) => {
				supplierName.value = res.Records;
				// console.log('supplierName:',supplierName.value[0].Status);
				tableData.value = supplierName.value.map((item) => ({
					ProductID: item.ProductID,
					Unit: item.Unit,
					Price: parseInt(item.Price),
					Amount: parseInt(item.Amount),
					BuyAmount: parseInt(item.BuyAmount),
					UseTime: parseInt(item.UseTime),
					ApplyID: item.ApplyID,
					NewBuyAmount: 0,
				}));
			});
		};
		queryData();
		async function myAsyncFunction() {
			// const SelData = selectedRows.value;
			let flag = false;
			const arr = ['SupplierID', 'CreditCode', 'BandName', 'BankAccount'];
			for (let index = 0; index < arr.length; index++) {
				const key = arr[index];
				if ([null, undefined].includes(fullSupplierInfo.value[key])) {
					flag = true;
					ElMessage.warning(`${key}字段为空`);
					break;
				}
			}
			if (flag) return;

			await httpRequest
				.Post(
					'addPurchaseApply',
					{},
					{
						selectProduct: selectedRows.value,
						ApplyID: selectedRows.value[0].ApplyID,
						SupplierID: fullSupplierInfo.value.SupplierID,
						CreditCode: fullSupplierInfo.value.CreditCode,
						BandName: fullSupplierInfo.value.BandName,
						BankAccount: fullSupplierInfo.value.BankAccount,
						PurchaseName: state.PurchaseName,
					}
				)
				.then((res) => {
					if (res.success) {
						ElMessage.success('下达成功');
						queryData();
					} else {
						ElMessage.error('下达失败');
					}
				});
		}
		const tableData = ref([]);

		const columns = [
			// { type: 'selection', width: '55' },
			{ prop: 'ProductID', label: '商品名' },
			{ prop: 'Price', label: '单价' },
			{ prop: 'Unit', label: '单位' },
			{ prop: 'Amount', label: '采购数量' },
			{ prop: 'BuyAmount', label: '已下达数量' },
			{ prop: '', label: '下达数量', component: ElInput, min: 0, precision: 0 },
		];

		// 计算每行的总金额
		const calculateTotalAmount = (row) => {
			return row.Price * (row.NewBuyAmount + row.BuyAmount);
		};

		// 更新输入框中的数量
		const updateNumber = (row) => {
			if (row.NewBuyAmount > row.Amount - row.BuyAmount) {
				row.NewBuyAmount = row.Amount - row.BuyAmount;
			}
		};

		const selectedRows = ref([]);
		const dialogVisible = ref(false);

		// 表格行选中事件处理方法
		const onSelectionChange = (selection) => {
			selectedRows.value = selection;
		};

		const submitData = () => {
			if (!state.PurchaseName) {
				ElMessage('请输入采购名称');
			} else if (selectedRows.value.length === 0) {
				ElMessage('请选择下达产品');
			} else {
				let allNonZero = true;
				for (let i = 0; i < selectedRows.value.length; i++) {
					if (selectedRows.value[i].NewBuyAmount === 0) {
						allNonZero = false;
						break;
					}
				}
				if (allNonZero) {
					nextTick(() => {
						console.log('selectedRows:', selectedRows.value);
						// dialogVisible.value = true; // 点击提交后弹出框打开
						myAsyncFunction();
					});
				} else {
					ElMessage('请添加下达产品');
				}
			}
		};

		const handleClose = () => {
			dialogVisible.value = false; // 点击确认后关闭弹出框
		};

		return {
			tableData,
			columns,
			calculateTotalAmount,
			updateNumber,
			selectedRows,
			onSelectionChange,
			submitData,
			ElMessage,
			dialogVisible,
			handleClose,
			fullSupplierInfo,
			...toRefs(state),
		};
	},
};
</script>
